package com.example.xmpic.ui.activity.local;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSnapHelper;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.SeekBar;

import com.example.common.base.BaseBindActivity;
import com.example.common.base.OnCallBackToRefresh;
import com.example.common.utils.DateUtil;
import com.example.common.utils.LiveDataBus;
import com.example.common.utils.MediaPlayerUtil;
import com.example.xmpic.R;
import com.example.xmpic.databinding.ActivityCameraRecordBinding;
import com.example.xmpic.support.FunError;
import com.example.xmpic.support.FunPath;
import com.example.xmpic.support.FunSupport;
import com.example.xmpic.support.OnFunDeviceOptListener;
import com.example.xmpic.support.OnFunDeviceRecordListener;
import com.example.xmpic.support.config.AVEncVideoWidget;
import com.example.xmpic.support.config.OPCompressPic;
import com.example.xmpic.support.models.FunDevRecordFile;
import com.example.xmpic.support.models.FunDevice;
import com.example.xmpic.support.models.FunFileData;
import com.example.xmpic.ui.adapter.RecordListAdapter;
import com.example.xmpic.ui.utils.LocalFileManager;
import com.example.xmpic.view.BaseImageDialog;
import com.example.xmpic.view.TimerScrollView;
import com.lib.SDKCONST;
import com.lib.sdk.struct.H264_DVR_FILE_DATA;
import com.lib.sdk.struct.H264_DVR_FINDINFO;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author skygge
 * @date 2020-01-25.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：视频回放页面
 */
public class CameraRecordActivity extends BaseBindActivity<ActivityCameraRecordBinding> implements
        OnFunDeviceRecordListener, OnFunDeviceOptListener,
        MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener,
        TimerScrollView.ScrollViewListener, SeekBar.OnSeekBarChangeListener, View.OnTouchListener {

    private static String TAG = CameraRecordActivity.class.getName();

    private int mCameraId;
    private FunDevice mFunDevice = null;
    private FunFileData mCurrentFile;
    private List<Map<String,Object>> mPlayList;
    private List<FunFileData> mRecordFiles;
    private static List<FunFileData> mChooseFiles;

    private final int REQUEST_SELECT_DATE  = 1;
    private final int MESSAGE_SEEK_PROGRESS = 0x101;
    private final int MESSAGE_HIDE_CONTROL = 0x102;
    private final int MESSAGE_SHOW_CONTROL = 0x103;
    private final int MESSAGE_TOAST_SCREENSHOT_PREVIEW = 0x104;
    private final int MESSAGE_SET_VIDEO_AT = 0x105;
    private final int MESSAGE_SET_VIDEO_IN = 0x106;
    private final int MESSAGE_REFRESH_PROGRESS = 0x107;

    private static final float TOTAL_PROCESS_HOUR = 4320f;//小时长度
    private static final float TOTAL_PROCESS_MINUTE = 25920f;//分钟长度

    private boolean mScrollStatus = false; //若为true表示进度条在被手指滑动
    private float mCurrent = -1f;  //若为true表示进度条在中间；并且不是同一段录像
    private AtomicBoolean isSounded = new AtomicBoolean(true);

    private Calendar mCalendar;
    private SimpleDateFormat mSimpleDf;
    private MediaPlayerUtil mMediaPlayer;

    private RecordListAdapter mAdapter;
    private String mDateTime;

    private boolean isScrollHour = true;
    private boolean isHasTimeView = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_camera_record;
    }

    @Override
    protected void initialize() {
        super.initialize();
        mCameraId = getIntent().getIntExtra("FUN_DEVICE_ID", 0);
        mFunDevice = FunSupport.getInstance().findDeviceById(mCameraId);
        if (null == mFunDevice) {
            finish();
            return;
        }
        // 1. 注册录像文件搜索结果监听 - 在搜索完成后以回调的方式返回
        FunSupport.getInstance().registerOnFunDeviceRecordListener(this);
        FunSupport.getInstance().registerOnFunDeviceOptListener(this);
        FunSupport.getInstance().requestDeviceConfig(mFunDevice, AVEncVideoWidget.CONFIG_NAME, mFunDevice.CurrChannel);
    }

    @Override
    protected void initView() {
        super.initView();
        mCalendar = Calendar.getInstance();
        mPlayList = new ArrayList<>();
        mRecordFiles = new ArrayList<>();
        mChooseFiles = new ArrayList<>();
        mDBind.recordChoose.setChecked(true);
        mDBind.recordTime.setVisibility(View.GONE);
        mDBind.loading.setVisibility(View.GONE);
        mDBind.scrollView.setHandler(mHandler);

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mDBind.recordList.setLayoutManager(manager);
        new LinearSnapHelper().attachToRecyclerView(mDBind.recordList);
    }

    @Override
    protected void initData() {
        super.initData();
        mSimpleDf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        onSearchFile();
        FunPath.onCreateSptTempPath(mFunDevice.getSerialNo());
    }

    @Override
    protected void initDataBus() {
        super.initDataBus();
        LiveDataBus.get().with("RECORD_PLAY", FunFileData.class).observe(this, funFileData -> {
            if (funFileData!=null){
                Message message = new Message();
                message.what = MESSAGE_SET_VIDEO_AT;
                message.obj = funFileData;
                mHandler.sendMessageDelayed(message, 10);
            }
        });

        LiveDataBus.get().with("RECORD_DOWNLOAD", Integer.class).observe(this, integer ->
                mDBind.downloadNavigation.setVisibility(View.VISIBLE));

        LiveDataBus.get().with("FUN_DEVICE_ID", Integer.class).observe(this, integer -> downloadCancel());
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initListener() {
        super.initListener();
        mDBind.ivRecordBack.setOnClickListener(view -> finish());
        mDBind.ivCalendar.setOnClickListener(v -> skipToChooseDateForResult());
        mDBind.scrollView.setOnScrollStateChangedListener(this);
        mDBind.funRecVideoView.setOnPreparedListener(this);
        mDBind.funRecVideoView.setOnErrorListener(this);
        mDBind.funRecVideoView.setOnCompletionListener(this);
        mDBind.funRecVideoView.setOnTouchListener(this);
        mDBind.recordSeekBar.setOnSeekBarChangeListener(this);

        mDBind.btPlay.setOnClickListener(v -> onVideoPlayControl());
        mDBind.btVoice.setOnClickListener(v -> onSoundControl());
        mDBind.btCapture.setOnClickListener(v -> tryToCapture());
        mDBind.btScreenRatio.setOnClickListener(v -> switchOrientation());
        mDBind.recordSuspend.setOnClickListener(v -> onVideoPlaySuspend());
        mDBind.recordLandscape.setOnClickListener(v -> setScreenAsPortrait());

        mDBind.recordChoose.setChecked(false);
        mDBind.recordChoose.setOnCheckedChangeListener((buttonView, isChecked) -> {
            isScrollHour = !isChecked;
            mDBind.scrollView.setHourOrMinute(isScrollHour);
            mDBind.scrollView.getHistoryView().setPlayList(mPlayList, isScrollHour);
            mDBind.recordHour.setVisibility(isChecked? View.VISIBLE : View.GONE);
            mDBind.recordMinute.setVisibility(!isChecked? View.VISIBLE : View.GONE);
        });

        mDBind.downloadSelectAll.setOnClickListener(v -> {
            mAdapter.selectAllFiles();
            mChooseFiles = mRecordFiles;
        });

        mDBind.downloadCancel.setOnClickListener(v -> downloadCancel());

        mDBind.downloadConfirm.setOnClickListener(v -> {
            mChooseFiles = mAdapter.getDownloadFiles();
            Intent intent = new Intent(mContext, RecordDownLoadActivity.class);
            intent.putExtra("FUN_DEVICE_ID", mCameraId);
            startActivity(intent);
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mDateTime = mSimpleDf.format(mCalendar.getTime());
        mDBind.tvRecordTitle.setText(mDateTime);
    }

    /**
     * 搜索视频文件
     */
    private void onSearchFile() {
        showProgressDialog();
        int[] time = {mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH) + 1, mCalendar.get(Calendar.DATE)};
        H264_DVR_FINDINFO info = new H264_DVR_FINDINFO();
        info.st_6_StreamType = SDKCONST.StreamType.Main;
        info.st_1_nFileType = SDKCONST.FileType.SDK_RECORD_ALL;
        info.st_2_startTime.st_0_dwYear = time[0];
        info.st_2_startTime.st_1_dwMonth = time[1];
        info.st_2_startTime.st_2_dwDay = time[2];
        info.st_2_startTime.st_3_dwHour = 0;
        info.st_2_startTime.st_4_dwMinute = 0;
        info.st_2_startTime.st_5_dwSecond = 0;
        info.st_3_endTime.st_0_dwYear = time[0];
        info.st_3_endTime.st_1_dwMonth = time[1];
        info.st_3_endTime.st_2_dwDay = time[2];
        info.st_3_endTime.st_3_dwHour = 23;
        info.st_3_endTime.st_4_dwMinute = 59;
        info.st_3_endTime.st_5_dwSecond = 59;
        info.st_0_nChannelN0 = mFunDevice.CurrChannel;
        FunSupport.getInstance().requestDeviceFileList(mFunDevice, info);
    }

    public static List<FunFileData> getChooseFiles() {
        return mChooseFiles;
    }

    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case MESSAGE_SEEK_PROGRESS:
                    seekRecordVideo((int)msg.obj);
                    break;
                case MESSAGE_HIDE_CONTROL:
                    //十秒后自动隐藏视频控制按钮
                    hideControlView();
                    break;
                case MESSAGE_SHOW_CONTROL:
                    showControlView();
                    break;
                case MESSAGE_TOAST_SCREENSHOT_PREVIEW:
                    String path = (String) msg.obj;
                    showScreenShotPreview(path);
                    break;
                case MESSAGE_SET_VIDEO_AT:
                    mCurrentFile = (FunFileData)msg.obj;
                    playRecordVideoByFile(mCurrentFile);
                    break;
                case MESSAGE_REFRESH_PROGRESS:
                    refreshProgress();
                    resetProgressInterval();
                    break;
                case MESSAGE_SET_VIDEO_IN:
                    Map<String,Object> data = (Map<String,Object>)msg.obj;
                    FunFileData current= (FunFileData)data.get("video");
                    float curr1 = (float)data.get("current");
                    Log.i(TAG, "handleMessage: " + curr1);
                    if (current!=null) {
                        if (mCurrentFile != null && current.getBeginTimeStr().equals(mCurrentFile.getBeginTimeStr())) {
                            seekRecordVideo(current, curr1);
                        } else {
                            mCurrentFile = current;
                            mCurrent = curr1;
                            playRecordVideoByFile(current);
                        }
                    }
                    break;
            }
            return false;
        }
    });

    /**
     * 播放回放视频文件
     */
    private void playRecordVideoByFile(FunFileData recordFile) {
        try {
            if(recordFile!=null && recordFile.getFileData()!=null){
                mDBind.funRecVideoView.stopPlayback();
                mDBind.loading.setVisibility(View.VISIBLE);
                mDBind.recordSuspend.setVisibility(View.GONE);
                mDBind.btPlay.setImageResource(R.mipmap.icon_play_on);
                mDBind.funRecVideoView.playRecordByFile(mFunDevice.getDevSn(), recordFile.getFileData(), mFunDevice.CurrChannel);
                mDBind.funRecVideoView.setMediaSound(isSounded.get());
                int beginTime = DateUtil.getSecondInDay(recordFile.getBeginTimeStr());
                int start= isScrollHour?beginTime/20:beginTime*3/10;
                mDBind.scrollView.smoothScrollTo(start,0);
                int mFileSize = mRecordFiles.size();
                for(int i=0; i < mFileSize; i++){
                    if(recordFile.getBeginTimeStr().equals(mRecordFiles.get(i).getBeginTimeStr())){
                        mDBind.recordList.scrollToPosition(i);
                        mAdapter.setPosition(i);
                        break;
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 播放所有回放视频/通过scroll
     */
    private void seekRecordVideo(FunFileData funFileData, float current) {
        if (null != funFileData) {
            int beginTime = DateUtil.getSecondInDay(funFileData.getBeginTimeStr());
            int endTime = DateUtil.getSecondInDay(funFileData.getEndTimeStr());
            float start = isScrollHour?beginTime/20f:beginTime*3f/10f;
            float end   = isScrollHour?endTime/20f:endTime*3f/10f;
            int progress = (int)((current-start)*100f/(end-start));
            mDBind.funRecVideoView.seekbyfile(progress);
        }
    }

    /**
     * 播放单个文件的进度/通过seekBar
     */
    private void seekRecordVideo(int progress) {
        mDBind.recordSeekBar.setProgress(progress);
        int seekPos = mDBind.funRecVideoView.getStartTime()+progress;
        mDBind.funRecVideoView.seek(seekPos);
    }

    /**
     * 实时刷新回放视频的进度
     */
    private void refreshProgress() {
        int posTm = mDBind.funRecVideoView.getPosition();
        if ( posTm > 0 ) {
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
            String time = mDateTime + "\t"+ sdf.format(new Date((long)posTm*1000));
            mDBind.recordTime.setText(time);
            if(!mScrollStatus){
                int beginTime =DateUtil.getSecondInDay(sdf.format(new Date((long)posTm*1000)));
                mDBind.scrollView.smoothScrollTo(isScrollHour?beginTime/20:beginTime*3/10,0);
            }
            mDBind.recordSeekBar.setProgress(posTm - mDBind.funRecVideoView.getStartTime());
        }
    }

    /**
     * 刷新回放视频内容
     */
    private void refreshPlayInfo() {
        int startTm = mDBind.funRecVideoView.getStartTime();
        int endTm = mDBind.funRecVideoView.getEndTime();
        if (startTm > 0 && endTm > startTm) {
            mDBind.recordSeekBar.setMax(endTm - startTm);
            mDBind.recordSeekBar.setProgress(0);
            mDBind.recordSeekBar.setVisibility(View.VISIBLE);
            resetProgressInterval();
        } else {
            mDBind.recordSeekBar.setVisibility(View.GONE);
            cleanProgressInterval();
        }
    }

    /**
     * 重置播放进度
     */
    private void resetProgressInterval() {
        if (null != mHandler ) {
            mHandler.removeMessages(MESSAGE_REFRESH_PROGRESS);
            mHandler.sendEmptyMessageDelayed(MESSAGE_REFRESH_PROGRESS, 500);
        }
    }

    /**
     * 关闭播放进度
     */
    private void cleanProgressInterval() {
        if ( null != mHandler ) {
            mHandler.removeMessages(MESSAGE_REFRESH_PROGRESS);
        }
    }

    /**
     * 选择日期
     */
    private void skipToChooseDateForResult(){
        Intent intent = new Intent(this, DateSelectActivity.class);
        intent.putExtra("FUN_DEVICE_ID", mFunDevice.getId());
        intent.putExtra("Date", mCalendar);
        startActivityForResult(intent, REQUEST_SELECT_DATE);
    }

    /**
     * 视频播放控制
     */
    private void onVideoPlayControl(){
        if (mDBind.funRecVideoView.isPlaying()) {
            mDBind.recordSuspend.setVisibility(View.VISIBLE);
            mDBind.btPlay.setImageResource(R.mipmap.icon_play);
            mDBind.funRecVideoView.pause();
        } else {
            mDBind.recordSuspend.setVisibility(View.GONE);
            mDBind.btPlay.setImageResource(R.mipmap.icon_play_on);
            mDBind.funRecVideoView.resume();
        }
    }

    /**
     * 回放暂停继续播放
     */
    private void onVideoPlaySuspend(){
        mDBind.recordSuspend.setVisibility(View.GONE);
        mDBind.btPlay.setImageResource(R.mipmap.icon_play_on);
        mDBind.funRecVideoView.resume();
    }

    /**
     * 声音控制
     */
    private void onSoundControl(){
        if (isSounded.get()) {
            isSounded.set(false);
            mDBind.btVoice.setImageResource(R.mipmap.icon_no_voice);
            mDBind.funRecVideoView.setMediaSound(false);
        } else {
            isSounded.set(true);
            mDBind.btVoice.setImageResource(R.mipmap.icon_is_voice);
            mDBind.funRecVideoView.setMediaSound(true);
        }
    }

    /**
     * 视频截图,并延时一会提示截图对话框
     */
    private void tryToCapture() {
        if (!mDBind.funRecVideoView.isPlaying()) {
            showToast(getString(R.string.media_capture_failure_need_playing));
            return;
        }
        mMediaPlayer = new MediaPlayerUtil(mContext);
        mMediaPlayer.playPhotograph();
        String path = mDBind.funRecVideoView.captureImage(mFunDevice.getDevSn());	//图片异步保存
        if (!TextUtils.isEmpty(path)) {
            Message message = new Message();
            message.what = MESSAGE_TOAST_SCREENSHOT_PREVIEW;
            message.obj = path;
            mHandler.sendMessageDelayed(message, 500);			//此处延时一定时间等待图片保存完成后显示，也可以在回调成功后显示
        }
    }

    /**
     * 显示截图成功对话框
     */
    private void showScreenShotPreview(String path) {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        BaseImageDialog mDialog = new BaseImageDialog(mContext, new OnCallBackToRefresh() {
            @Override
            public void onConfirm() {
                File imgPath = new File(path);
                if (imgPath.exists()) {
                    String d = String.format(getResources().getString(R.string.device_socket_capture_save_success), path);
                    showToast(d);
                }
                LocalFileManager.getInstance().scanFile(mContext, path);
            }

            @Override
            public void onCancel() {
                FunPath.deleteFile(path);
                showToast(getString(R.string.device_socket_capture_delete_success));
            }
        });
        mDialog.setImageAndButton(bitmap, getString(R.string.delete), getString(R.string.save));
        mDialog.show();
    }

    /**
     * 切换视频全屏/小视频窗口(以切横竖屏切换替代)
     */
    @SuppressLint("SourceLockedOrientationActivity")
    private void switchOrientation() {
        // 横竖屏切换
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                && getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
        } else if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    /**
     * 关闭下载功能
     */
    private void downloadCancel(){
        mAdapter.cancelDownload();
        mDBind.downloadNavigation.setVisibility(View.GONE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode!=RESULT_OK) return;
        if(requestCode==REQUEST_SELECT_DATE){
            mPlayList.clear();
            mRecordFiles.clear();
            int result_year = data.getExtras().getInt("year");
            int result_month = data.getExtras().getInt("month");
            int result_day   = data.getExtras().getInt("day");
            mCalendar.set(result_year, result_month, result_day);
            onSearchFile();
        }
    }

    @Override
    public void onDeviceLoginSuccess(FunDevice funDevice) {

    }

    @Override
    public void onDeviceLoginFailed(FunDevice funDevice, Integer errCode) {

    }

    @Override
    public void onDeviceGetConfigSuccess(FunDevice funDevice, String configName, int nSeq) {
        AVEncVideoWidget avEnc = (AVEncVideoWidget) mFunDevice.getConfig(AVEncVideoWidget.CONFIG_NAME);
        if (null != avEnc) {
            isHasTimeView = avEnc.timeTitleAttribute.EncodeBlend;
        }
    }

    @Override
    public void onDeviceGetConfigFailed(FunDevice funDevice, Integer errCode) {

    }

    @Override
    public void onDeviceSetConfigSuccess(FunDevice funDevice, String configName) {

    }

    @Override
    public void onDeviceSetConfigFailed(FunDevice funDevice, String configName, Integer errCode) {

    }

    @Override
    public void onDeviceChangeInfoSuccess(FunDevice funDevice) {

    }

    @Override
    public void onDeviceChangeInfoFailed(FunDevice funDevice, Integer errCode) {

    }

    @Override
    public void onDeviceOptionSuccess(FunDevice funDevice, String option) {

    }

    @Override
    public void onDeviceOptionFailed(FunDevice funDevice, String option, Integer errCode) {

    }

    @Override
    public void onDeviceFileListChanged(FunDevice funDevice) {

    }

    @Override
    public void onDeviceFileListChanged(FunDevice funDevice, H264_DVR_FILE_DATA[] datas) {
            if (null != funDevice && null != mFunDevice && funDevice.getId() == mFunDevice.getId()) {
                if (datas.length>0){
                    for (H264_DVR_FILE_DATA data : datas) {
                        FunFileData funFileData = new FunFileData(data, new OPCompressPic());
                        int beginTime = DateUtil.getSecondInDay(funFileData.getBeginTimeStr());
                        int endTime = DateUtil.getSecondInDay(funFileData.getEndTimeStr());
                        int type = funFileData.getFileType();
                        Map<String,Object> map = new HashMap<>();
                        map.put("start",beginTime);
                        map.put("end",endTime);
                        map.put("type",type);
                        mPlayList.add(map);
                        mRecordFiles.add(funFileData);
                    }
                }
                showRecordVideo();
        }
    }

    @Override
    public void onDeviceFileListGetFailed(FunDevice funDevice) {}

    @Override
    public void onRequestRecordListSuccess(List<FunDevRecordFile> files) {
    }

    @Override
    public void onRequestRecordListFailed(Integer errCode) {
        noRecordVideo();
    }

    @Override
    public void onScrollChanged(TimerScrollView.ScrollType scrollType) {
        float mScrollX;
        if(scrollType != TimerScrollView.ScrollType.IDLE){
            mScrollStatus = true;
            return;
        }
        mScrollStatus = false;
        if(mDBind.scrollView.getScrollX()<0){
            mScrollX = 0f;
        }else if(mDBind.scrollView.getScrollX() > (isScrollHour ? TOTAL_PROCESS_HOUR : TOTAL_PROCESS_MINUTE)){
            mScrollX = isScrollHour ? TOTAL_PROCESS_HOUR : TOTAL_PROCESS_MINUTE;
        }else{
            mScrollX = (float)mDBind.scrollView.getScrollX();
        }

        for(int i=0; i<mRecordFiles.size();i++){
            int beginTime = DateUtil.getSecondInDay(mRecordFiles.get(i).getBeginTimeStr());
            int endTime = DateUtil.getSecondInDay(mRecordFiles.get(i).getEndTimeStr());
            float x = (isScrollHour?beginTime/20f:beginTime*3f/10f);
            float x2 = (isScrollHour?endTime/20f:endTime*3f/10f);
            if(x > mScrollX){
                Message message = new Message();
                message.what = MESSAGE_SET_VIDEO_AT;
                message.obj = mRecordFiles.get(i);
                mHandler.sendMessageDelayed(message, 10);
                break;
            }else if(x<=mScrollX && x2>=mScrollX){
                Message message = new Message();
                message.what = MESSAGE_SET_VIDEO_IN;
                Map<String,Object> ds = new HashMap<>();
                ds.put("video", mRecordFiles.get(i));
                ds.put("current",mScrollX);
                message.obj = ds;
                mHandler.sendMessageDelayed(message, 10);
                break;
            }
        }
    }

    /**
     * 显示当天有录像
     */
    private void showRecordVideo(){
        dismissProgressDialog();
        if(mRecordFiles.size()>0){
            mCurrentFile = mRecordFiles.get(0);
            if (mAdapter!=null){
                mAdapter.release();
            }
            mAdapter = new RecordListAdapter(this, mFunDevice);
            mAdapter.setFiles(mRecordFiles, mDBind.recordList);
            mDBind.recordList.setAdapter(mAdapter);
            mDBind.recordNone.setVisibility(View.GONE);
            mDBind.funRecVideoView.setVisibility(View.VISIBLE);
            mDBind.recordList.setVisibility(View.VISIBLE);
            mDBind.player.setVisibility(View.VISIBLE);
            mDBind.recordTime.setVisibility(isHasTimeView ? View.GONE : View.VISIBLE);
            mDBind.recordTimeSwitch.setVisibility(View.VISIBLE);
            mDBind.scrollView.getHistoryView().setPlayList(mPlayList, isScrollHour);
            playRecordVideoByFile(mCurrentFile);
        }else{
            showToast(getString(R.string.device_camera_video_list_empty));
            mDBind.player.setVisibility(View.GONE);
            mDBind.recordTime.setVisibility(View.GONE);
        }
    }

    /**
     * 显示当天没有录像
     */
    private void noRecordVideo(){
        dismissProgressDialog();
        mPlayList.clear();
        mRecordFiles.clear();
        mDBind.player.setVisibility(View.GONE);
        mDBind.recordSeekBar.setProgress(0);
        mDBind.recordSeekBar.setVisibility(View.GONE);
        mDBind.recordTime.setVisibility(View.GONE);
        mDBind.recordList.setVisibility(View.GONE);
        mDBind.recordNone.setVisibility(View.VISIBLE);
        showToast(getString(R.string.no_video));
        mDBind.funRecVideoView.stopPlayback();
        mDBind.funRecVideoView.setVisibility(View.GONE);
        mDBind.recordTimeSwitch.setVisibility(View.GONE);
    }

    @Override
    public boolean onError(MediaPlayer mediaPlayer, int i, int extra) {
        showToast(getString(R.string.media_play_error) + " : " +FunError.getErrorStr(extra));
        return true;
    }

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        mDBind.loading.setVisibility(View.GONE);
        refreshPlayInfo();
        if(mCurrent != -1f){
            seekRecordVideo(mCurrentFile, mCurrent);
            mCurrent = -1f;
        }
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        if(null != mCurrentFile){
            for(int i=0; i  < mRecordFiles.size(); i++){
                if(mCurrentFile.getBeginTimeStr().equals(mRecordFiles.get(i).getBeginTimeStr())){
                    if(i<(mRecordFiles.size()-1)){
                        mCurrentFile = mRecordFiles.get(i+1);
                        playRecordVideoByFile(mCurrentFile);
                    }
                    break;
                }
            }
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser) {
            mHandler.removeMessages(MESSAGE_SEEK_PROGRESS);
            mHandler.obtainMessage(MESSAGE_SEEK_PROGRESS, progress).sendToTarget();
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // 检测屏幕的方向：纵向或横向
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            // 当前为横屏， 在此处添加额外的处理代码
            showAsLandscape();
        }else if(getResources().getConfiguration().orientation ==Configuration.ORIENTATION_PORTRAIT) {
            // 当前为竖屏， 在此处添加额外的处理代码
            showAsPortrait();
        }
        super.onConfigurationChanged(newConfig);
    }

    // 视频窗口全屏显示
    private void showAsLandscape() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        LinearLayout.LayoutParams mParams = (LinearLayout.LayoutParams) mDBind.layoutPlayView.getLayoutParams();
        mParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
        mDBind.layoutPlayView.setLayoutParams(mParams);
        mDBind.btScreenRatio.setImageResource(R.mipmap.icon_full_back);
        mDBind.layoutTop.setVisibility(View.GONE);
        mDBind.layoutPlayButton.setVisibility(View.GONE);
        mDBind.recordLandscape.setVisibility(View.VISIBLE);
        mHandler.sendEmptyMessageDelayed(MESSAGE_HIDE_CONTROL, 10000);
    }

    // 视频显示为小窗口
    private void showAsPortrait() {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        mHandler.removeMessages(MESSAGE_HIDE_CONTROL);
        LinearLayout.LayoutParams mParams = (LinearLayout.LayoutParams) mDBind.layoutPlayView.getLayoutParams();
        mParams.height = (int)getResources().getDimension(R.dimen.margin_276);
        mDBind.layoutPlayView.setLayoutParams(mParams);
        mDBind.btScreenRatio.setImageResource(R.mipmap.icon_full);
        mDBind.layoutTop.setVisibility(View.VISIBLE);
        mDBind.layoutPlayButton.setVisibility(View.VISIBLE);
        mDBind.recordLandscape.setVisibility(View.GONE);
    }

    //显示视频控制栏
    private void showControlView(){
        mDBind.layoutVideoControl.setVisibility(View.VISIBLE);
    }

    //隐藏视频控制栏
    private void hideControlView(){
        mDBind.layoutVideoControl.setVisibility(View.GONE);
    }

    @SuppressLint("SourceLockedOrientationActivity")
    private void setScreenAsPortrait(){
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        mHandler.removeMessages(MESSAGE_HIDE_CONTROL);
        mHandler.obtainMessage(MESSAGE_SHOW_CONTROL).sendToTarget();
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_MOVE:
                mHandler.obtainMessage(MESSAGE_SHOW_CONTROL).sendToTarget();
                mHandler.removeMessages(MESSAGE_HIDE_CONTROL);
                mHandler.sendEmptyMessageDelayed(MESSAGE_HIDE_CONTROL, 10000);
                break;
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        // 如果当前是横屏，返回时先回到竖屏
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setScreenAsPortrait();
            return;
        }
        finish();
    }

    @Override
    protected void onDestroy() {
        // 停止视频播放
        mDBind.funRecVideoView.stopPlayback();
        // 5. 退出注销监听
        FunSupport.getInstance().removeOnFunDeviceRecordListener(this);
        FunSupport.getInstance().removeOnFunDeviceOptListener(this);
        if ( null != mHandler ) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        if (mMediaPlayer!=null){
            mMediaPlayer.destroy();
        }
        super.onDestroy();
    }
}
